package com.example.seakdreamandroid.bonus;

import static com.example.seakdreamandroid.Constant.BASE_URL;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.crosstalk.Audio;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.lottery.Lottery;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BonusPointsActivity extends AppCompatActivity {
    TextView TodayPoints;
    ListView bonusTaskList;
    ListView exchangeList;
    List<Map<String,Object>> pointsTaskList = new ArrayList();
    User user;
    private ScrollView mScrollView;
    RelativeLayout tv01;
    RelativeLayout tv02;
    RelativeLayout mLinearLayout;

    BonusPointsAdapter bonusPointsAdapter;
    ImageButton returnButton;


    TextView totalPoint;
    private static String userPoints;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bonus_points);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0 全透明实现
            //getWindow.setStatusBarColor(Color.TRANSPARENT)
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4 全透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        user = (User)getApplication();

        setTotalPoint();
        setBonusTaskList();
        setExchangeList();

        initView();
        setReturnButtonOnclickListener();
        setOnClickListener();

        System.out.println(userPoints);
    }

    //返回按钮点击返回“我的”页面
    private void setReturnButtonOnclickListener() {
        returnButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BonusPointsActivity.this.finish();
            }
        });
    }

    //显示总积分
    public void setTotalPoint() {
        totalPoint = findViewById(R.id.dataTotalPoint);
        String userId = user.getUserId();
        Request request = new Request.Builder()
                //设置请求的地址，默认的请求方式是Get请求
                .url(BASE_URL+"UserInfo/getUserInfo"+"?id="+userId)
                //创建Request对象
                .build();
        //3.发送请求，获取响应
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        //发起异步的请求，不需要手动创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调
                Log.e("BonusPointsActivity","onFailure，请求数据失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(BonusPointsActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();

                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //请求成功时回调
                Log.i("BonusPointsActivity","onResponse"+"成功");
                try {
                    String resultStr = response.body().string();
                    JSONObject object = new JSONObject(resultStr);
                    JSONObject data = object.getJSONObject("data");
                    if(!data.isNull("points")){
                        userPoints = data.getString("points");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                totalPoint.setText(userPoints);
                            }
                        });

                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
                //setview
            }
        });
    }


    public void setBonusTaskList() {
        bonusTaskList = findViewById(R.id.pointsList);

//        pointsTaskList.add(new PointsTask("完成睡眠记录一次"));
//        pointsTaskList.add(new PointsTask("社区点赞一次"));
//        pointsTaskList.add(new PointsTask("增加哄睡值一次"));


        Request request = new Request.Builder()
                //设置请求的地址，默认的请求方式是Get请求
                .url(BASE_URL+"Bonus/getAllTask")
                //创建Request对象
                .build();
        //3.发送请求，获取响应
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        //发起异步的请求，不需要手动创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调
                Log.e("OkHttp","onFailure");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功时回调
                String result = response.body().string();

                BonusPointsActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ArrayList<Audio> Audios = new ArrayList<>();
                            List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
                            JSONArray array = new JSONArray(result);
                            Map<String,Object> map1 = new HashMap<String,Object>();
                            for (int n=0;n<array.length();n++){
                                Map<String,Object> map = new HashMap<String,Object>();
                                JSONObject object1 = (JSONObject) array.get(n);
                                map.put("id",object1.getInt("id"));
                                map.put("Mission",object1.getString("mission"));
                                map.put("Button",(object1.getInt("key")));
                                map.put("point",object1.getInt("num"));
                                map.put("done",object1.getInt("isdone"));
                                Log.v("isdone",object1.getInt("isdone")+object1.getString("mission"));
                                list.add(map);
                            }

                            pointsTaskList.addAll(list);
                            System.out.println(pointsTaskList.get(0));
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        System.out.println(11111111);
                        bonusPointsAdapter = new BonusPointsAdapter(BonusPointsActivity.this,pointsTaskList);
                        bonusTaskList.setAdapter(bonusPointsAdapter);
                        setListViewHeightBasedOnChildren(bonusTaskList);

                    }
                });

            }
        });



    }

    public void setExchangeList() {
        exchangeList = findViewById(R.id.exchange_list);
        List<ExchangeBonus> exchangeBonusList = new ArrayList<>();
        exchangeBonusList.add(new ExchangeBonus(1,"小睡眠1天会员",100,"af"));
        exchangeBonusList.add(new ExchangeBonus(1,"小睡眠3天会员",150,"af"));
        exchangeBonusList.add(new ExchangeBonus(1,"小睡眠7天会员",250,"af"));
        exchangeBonusList.add(new ExchangeBonus(1,"小睡眠15天会员",400,"af"));
        exchangeBonusList.add(new ExchangeBonus(1,"2023青岛麦浪音乐节门票",800,"af"));

        exchangeBonusList.add(new ExchangeBonus(1,"积分抽奖",60,"af"));
        ExchangeBonusAdapter exchangeBonusAdapter = new ExchangeBonusAdapter(this,exchangeBonusList,user);
        exchangeList.setAdapter(exchangeBonusAdapter);
        setListViewHeightBasedOnChildren(exchangeList);
    }

    public void setNewPoints(int points){
        if (points<0){
            Toast toast = Toast.makeText(this,"积分不足，兑换失败",Toast.LENGTH_LONG);
            toast.show();
        }else{
            FormBody body = new FormBody.Builder()
                    .add("userId",user.getUserId())
                    .add("points", String.valueOf(points))
                    .build();
            //3.创建请求对象（Request）
            Request request = new Request.Builder()
                    //设置
                    .url(Constant.BASE_URL + "UserInfo"+"/updatePoints")
                    .post(body)//设置请求方式为POST，添加了请求体
                    //创建Request对象
                    .build();
            //4.发送请求，获取响应
            OkHttpClient okHttpClient = new OkHttpClient();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("msg","失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("bonusUpdate","成功");
                            user.setPoints(points);
                            totalPoint.setText(points+"");
                            bonusPointsAdapter.notifyDataSetChanged();
                        }
                    });
                }
            });
        }

    }








    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if(listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for(int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }






    private void initView() {
        mScrollView = (ScrollView) findViewById(R.id.scrollview_bonus);
        tv01 = (RelativeLayout) findViewById(R.id.tv01);
        tv02 = (RelativeLayout) findViewById(R.id.tv02);
        mLinearLayout = (RelativeLayout) findViewById(R.id.title_bonus);
        returnButton = (ImageButton) findViewById(R.id.returnBtn);
    }
    @TargetApi(Build.VERSION_CODES.M)
    private void setOnClickListener() {
        //mScrollView滑动监听
        mScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                //获取tv01、tv01控件的高度
                int height = tv01.getMeasuredHeight()+tv02.getMeasuredHeight();
                if (scrollY <= 0){
                    //滑动之前，标题栏布局背景颜色为完全透明，标题文字完全透明
                    mLinearLayout.setBackgroundColor(Color.argb(0,0,0,0));
                    //让mScrollView滑动的距离在0~height之间时颜色发生渐变
                }else if(scrollY >0 && scrollY <= height){
                    //获取渐变率
                    float scale = (float) scrollY / height;
                    //获取渐变数值
                    float alpha = (255 * scale);
                    //布局文本颜色逐渐发生变化
                    mLinearLayout.setBackgroundColor(Color.argb((int) alpha,245,245,245));
                }else {
                    //当滑动距离超过height，布局文本颜色完全不透明
                    mLinearLayout.setBackgroundColor(Color.argb(255,245,245,220));
                }
            }
        });
    }



}
